package com.bingkaimedia.merchantbeta.app;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.bingkaimedia.merchantbeta.R;
import com.bingkaimedia.merchantbeta.libs.AlertDialogManager;
import com.bingkaimedia.merchantbeta.libs.SessionManager;
import com.bingkaimedia.merchantbeta.libs_image.Utils;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

import vn.keho.define.convert.JsonUtil;
import vn.keho.module.dompeto.MerchantActivity;
import vn.keho.module.dompeto.model.LoginResponse;
import vn.keho.module.dompeto.rest.DompetoDefine;
import vn.keho.module.dompeto.rest.DompetoParam;
import vn.keho.module.dompeto.rest.DompetoRequest;


@SuppressLint("NewApi")
public class Signin extends Activity {

    //private SQLiteDB_Account account;
    private Button cmd_signin_signin;

    private EditText txt_signin_username;
    private EditText txt_signin_password;
    protected String user1;
    protected String pwd1;
    private String appid;
    private String ip;
    private String manufacturer;
    private String model;
    private String deviceid;
    private String os;
    private String latitude;
    private String longitude;

    private LocationManager locationMangaer = null;
    private LocationListener locationListener = null;
    private Boolean flag = false;

    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    public String result;


    public static final String KEY_SIGNIN_resp = "resp";
    public static final String KEY_SIGNIN_token = "token";
    public static final String KEY_SIGNIN_loginstatus = "loginstatus";
    public static final String KEY_SIGNIN_loginnotification = "loginnotification";
    public static final String KEY_SIGNIN_updateappsidstatus = "updateappsidstatus";
    public static final String KEY_SIGNIN_appsidstatus = "appsidstatus";
    public static final String KEY_SIGNIN_appsidonapps = "appsidonapps";
    public static final String KEY_SIGNIN_firstimestatus = "firstimestatus";
    public static final String KEY_SIGNIN_verificationstatus = "verificationstatus";
    public static final String KEY_SIGNIN_verificationnotification = "verificationnotification";
    public static final String KEY_SIGNIN_pinstatus = "pinstatus";
    public static final String KEY_SIGNIN_pinnotification = "pinnotification";
    public static final String KEY_SIGNIN_appsver = "appsver";
    public static final String KEY_SIGNIN_debug = "debug";


    private String xml_signin_resp;
    private String xml_signin_token;
    private String xml_signin_loginstatus;
    private String xml_signin_loginnotification;
    private String xml_signin_updateappsidstatus;
    private String xml_signin_appsidstatus;
    private String xml_signin_appsidonapps;
    private String xml_signin_firstimestatus;
    private String xml_signin_verificationstatus;
    private String xml_signin_verificationnotification;
    private String xml_signin_pinstatus;
    private String xml_signin_pinnotification;
    private String xml_signin_appsver;
    private String xml_signin_debug;

    public String url;
    protected String u1;
    protected String p1;
    public ProgressDialog pd;

    private static String session_userid;
    private static String session_username;
    private static String session_password;
    private static String session_email;
    private static String session_country;
    private static String session_country_name;
    private static String session_city;
    private static String session_city_name;
    private static String session_checked;

    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    // Session Manager Class
    SessionManager session;


    private ProgressDialog progressDialog;

    Button button;
    int typeBar;
    int delay = 0;                  // Milliseconds of delay in the update loop
    int maxBarValue = 0;           // Maximum value of horizontal progress bar


    int count;

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        setContentView(R.layout.signin);


        inisialisasi();
        form_click();

        session = new SessionManager(getApplicationContext());


    }


    private void inisialisasi() {


        txt_signin_username = (EditText) findViewById(R.id.txt_signin_username);
        txt_signin_password = (EditText) findViewById(R.id.txt_signin_password);
        cmd_signin_signin = (Button) findViewById(R.id.cmd_signin_sigin);


        Typeface font = Typeface.createFromAsset(getAssets(), "gisha.ttf");


        txt_signin_username.setTypeface(font);
        txt_signin_password.setTypeface(font);
        cmd_signin_signin.setTypeface(font);


        appid = Installation.id(getApplicationContext());
        ip = Utils.getIPAddress(true);
        manufacturer = Build.MANUFACTURER;
        model = Build.MODEL;
        deviceid = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
        os = Build.VERSION.RELEASE;


        GPSTracker gps;
        gps = new GPSTracker(Signin.this);

        // check if GPS enabled     
        if (gps.canGetLocation()) {
            latitude = String.valueOf(gps.getLatitude());
            longitude = String.valueOf(gps.getLongitude());
        } else {
            gps.showSettingsAlert();
        }


        System.out.println(appid);
        System.out.println(ip);
        System.out.println(manufacturer);
        System.out.println(model);
        System.out.println(deviceid);
        System.out.println(os);
        System.out.println(latitude);
        System.out.println(longitude);
    }


    private void form_click() {
        cmd_signin_signin.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                //account.openToRead();
                user1 = txt_signin_username.getText().toString().trim();
                pwd1 = txt_signin_password.getText().toString().trim();
                //account.close();


                //System.out.println("isonline "+isonline());
                if (isonline() == false) {
                    alert.showAlertDialog(Signin.this, "Information", "Tidak terhubung dengan internet.", false);
                } else if (isonline() == true) {
                    callRequestLogin();
                } else {
                    //System.out.println("masuk else isonline");
                }

            }

        });
    }


    private void showProgressDialog(boolean isShow) {
        if (isShow) {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(Signin.this);
            }
            //progressDoalog.setMax(20);
            progressDialog.setMessage("Please wait...");
            progressDialog.setTitle("Login");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();
            count = 30;
            handle.postDelayed(updateLoaderWaiting, 1000);
        } else {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            handle.removeCallbacks(updateLoaderWaiting);
        }
    }

    private Handler handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ////System.out.println("message handle "+msg);
            //progressDoalog.incrementProgressBy(1);

            progressDialog.setMessage("Please wait..." + count);
        }
    };

    private Runnable updateLoaderWaiting = new Runnable() {
        @Override
        public void run() {
            progressDialog.setMessage("Please wait..." + count);
            count--;
            if (count > 0) {
                handle.postDelayed(updateLoaderWaiting, 1000);
            } else {
                progressDialog.dismiss();
            }
        }
    };

    private void callRequestLogin() {
        user1 = txt_signin_username.getText().toString().trim();
        pwd1 = txt_signin_password.getText().toString().trim();
        try {
            showProgressDialog(true);
            DompetoParam params = new DompetoParam(DompetoDefine.URL_MERCHANT_LOGIN);
            params.setUsername(user1);
            params.setPassword(pwd1);
            new DompetoRequest(Signin.this, new DompetoRequest.AsyncCallbackRequestHandler() {
                @Override
                public void handlerRequestSuccess(Object data) {
                    try {
                        JSONArray jsonArray = new JSONArray(data.toString());
                        JSONObject jsonObject = jsonArray.getJSONObject(0);
                        LoginResponse loginResponse = JsonUtil.generateJavaObject(jsonObject.toString(), LoginResponse.class);
                        showProgressDialog(false);
                        if(loginResponse.getMloginstatus()) {
                            DompetoRequest.mappsidonapps = loginResponse.getMappsidonapps();
                            DompetoRequest.username = user1;
                            DompetoRequest.token = loginResponse.getToken();
                            DompetoRequest.channelid = loginResponse.getChannelid();

                            startActivity(new Intent(Signin.this, MerchantActivity.class));
                        } else {
                            startActivity(new Intent(Signin.this, Notification.class));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void handlerRequestError(String message) {
                    Log.i("Response", message);
                    showProgressDialog(false);
                }
            }).executeStart(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isonline() {

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }


}
